package com.fuluwa.interfaces.file.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fuluwa.infra.context.ThreadAttribute;
import com.fuluwa.infra.web.AbstractDomainController;
import com.fuluwa.infra.web.Result;
import com.fuluwa.interfaces.file.facade.FileServiceFacade;
import com.fuluwa.interfaces.knowledge.web.FileUploadListener;

@Controller
@RequestMapping(value = "/file")
public class FileUploadController extends AbstractDomainController {
	@Autowired
	FileServiceFacade fileServiceFacade;

	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public Result upload(@RequestParam("file") MultipartFile file) {
		try {
			Long fileId = fileServiceFacade.saveFile(file);
			ThreadAttribute.clearAll();
			return getSuccessResult(fileId);
		} catch (Exception e) {
			logger.error("error", e);
			return getFailResult("File upload Failed:" + e.getMessage());
		}
	}
	
	@RequestMapping(value = "uploadprogress", method = RequestMethod.GET)
	@ResponseBody
	public Result uploadprogress(HttpServletRequest request) {
		try {

			HttpSession session = request.getSession(true);
			if (session == null) {
				return getFailResult("Sorry, session is null");
			}

//			FileUploadListener uploadProgressListener = (FileUploadListener) ThreadAttribute.get(ThreadAttribute.FILE_UPLOAD);
			FileUploadListener uploadProgressListener = (FileUploadListener) session.getAttribute("uploadProgressListener");
			if (uploadProgressListener == null) {
				return getFailResult("Progress listener is null");
			}
			
			int ret = uploadProgressListener.getPercentage();
			return getSuccessResult(ret);
		} catch (Exception e) {
			logger.error("error", e);
			return getFailResult("File upload Failed:" + e.getMessage());
		}
	}

}
